package org.neogenesis.web.dao;

import java.io.Serializable;
import java.util.List;


import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

import org.neogenesis.web.model.SampleType;

import org.neogenesis.web.qualifier.DataRepository;

/**
 * @author Nancy
 * 
 */

public class SampleTypeDAO implements Serializable {

	@Inject
	@DataRepository
	private EntityManager em;
	
	public SampleTypeDAO() {
		// TODO Auto-generated constructor stub
	}

	public void create(SampleType sampleType) {
		em.persist(sampleType);
	}

	public void edit(SampleType sampleType) {
		em.merge(sampleType);
	}

	public void remove(SampleType sampleType) {
		em.remove(em.merge(sampleType));
	}

	public SampleType find(Object id) {
		return em.find(SampleType.class, id);
	}

	public List<SampleType> findAll() {
		CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
		cq.select(cq.from(SampleType.class));
		return em.createQuery(cq).getResultList();
	}

	public List<SampleType> findRange(int[] range) {
		CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
		cq.select(cq.from(SampleType.class));
		javax.persistence.Query q = em.createQuery(cq);
		q.setMaxResults(range[1] - range[0]);
		q.setFirstResult(range[0]);
		return q.getResultList();
	}

	public int count() {
		javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder()
				.createQuery();
		javax.persistence.criteria.Root<SampleType> rt = cq
				.from(SampleType.class);
		cq.select(em.getCriteriaBuilder().count(rt));
		javax.persistence.Query q = em.createQuery(cq);
		return ((Long) q.getSingleResult()).intValue();
	}

	public SampleType findByName(String name) {
		Query query = em.createQuery(
				"SELECT o FROM SampleType o WHERE o.name = :name",
				SampleType.class);
		query.setParameter("name", name);

		List<SampleType> sampleType = query.getResultList();

		if (sampleType.size() > 0)
			return sampleType.get(0);

		return null;
	}
}
